package process

import (
	"github.com/lishimeng/go-log"
	"strings"
)

func (c *AnalysisContext) procPreAnalysis() (doNext bool) {

	for index, keywordsInput := range c.input {
		select {
		case <-c.ctx.Done():
			return
		default:
			c.preAnalysis(index, keywordsInput)
		}
	}
	for _, kwi := range c.keywordIndexes {
		select {
		case <-c.ctx.Done():
			return
		default:
			c.preAnalysis2(kwi)
		}
	}
	log.Info("打印搜索词次数......")
	for kw, count := range c.keywordCount {
		log.Info("%s:\t%d", kw, count)
	}

	for _, kwi := range c.keywordIndexes {
		select {
		case <-c.ctx.Done():
			return
		default:
			c.preAnalysis3(kwi)
		}
	}

	log.Info("打印搜索词用户搜索原词......")
	for kw, list := range c.keywordsMap {
		log.Info("%s:\t%d", kw, c.keywordCount[kw])
		for _, index := range list {
			log.Info("\t%s", c.input[index].CustomSearch)
		}
	}

	doNext = true
	return
}

func (c *AnalysisContext) preAnalysis(index int, keywordsInput KeywordsInput) {
	customerInput := keywordsInput.CustomSearch
	customerKeywords := strings.Split(customerInput, " ")
	for _, kw := range customerKeywords {
		if EmptyFilter {
			if emptyFilter(kw) {
				return
			}
		}
		if NumberFilter {
			if numberFilter(kw) {
				return
			}
		}
		if SkipWordFilter {
			if skipWordsFilter(kw) {
				return
			}
		}
		c.keywordIndexes = append(c.keywordIndexes, KeywordIndex{
			Keyword: kw,
			Index:   index,
		})
	}
}

func (c *AnalysisContext) preAnalysis2(kwi KeywordIndex) { // keyword count
	kw := kwi.Keyword
	count, ok := c.keywordCount[kw]
	if !ok {
		c.keywordCount[kw] = 1
	} else {
		c.keywordCount[kw] = count + 1
	}
}

func (c *AnalysisContext) preAnalysis3(kwi KeywordIndex) { // keyword index_list
	kw := kwi.Keyword

	var indexList []int
	list, ok := c.keywordsMap[kw]
	if ok {
		indexList = list
	}
	indexList = append(indexList, kwi.Index)
	c.keywordsMap[kw] = indexList
}
